package com.reader.api.pay.utils;

import com.google.common.collect.Maps;
import com.reader.api.pay.model.Order;
import com.reader.api.pay.request.PayRequest;
import com.reader.api.utils.WXPayAssistUtil;
import com.reader.core.utils.HttpUtils;
import com.reader.core.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 微信支付.
 *
 * https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
 * https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_3
 * @author liujianqing
 * @date 2018/10/28
 */
public class WeixinPayUtil {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WeixinPayUtil.class);
    // 微信下发的商户号
    private static final String MCHID="";
    private static final String WX_APPID="";
    private static final String BODY="读者知识付费商品";
    private static final String WX_PAY_CALLBACK="";
    private static final String TRADE_TYPE = "APP";
    private static final String WX_PAY_KEY = "APPWX_PAY_KEY";
    private static final String PAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    public static String commitToWxPay(PayRequest payRequest, Order order) {
        String nonceStr = WXPayAssistUtil.generateNonceStr();

        final Map<String, String> map = Maps.newHashMap();
        map.put("body", BODY);
        map.put("mch_id", MCHID);
        map.put("appid", WX_APPID);
        map.put("nonce_str", nonceStr);
        map.put("notify_url", WX_PAY_CALLBACK);
        map.put("spbill_create_ip", payRequest.getIp());
        map.put("out_trade_no", payRequest.getOrderNum());
        map.put("total_fee", order.getPayPrice() + "");
        map.put("trade_type", TRADE_TYPE);

        //这步可以不要，为了排查加上sign log.
        String sign = null;
        try {
            sign = WXPayAssistUtil.generateSignature(map,WX_PAY_KEY);
        } catch (Exception e) {
            logger.info("签名失败 orderNum:{}",order.getOrderNum());
            return StringUtils.EMPTY;
        }

        String commtiPayXml = null;
        try {
            commtiPayXml = WXPayAssistUtil.generateSignedXml(map, WX_PAY_KEY);
        } catch (Exception e) {
            logger.info("生成commtiPayXml失败 orderNum:{}",order.getOrderNum());
            return StringUtils.EMPTY;
        }

        logger.info("发送给微信的报文：" + commtiPayXml);
        logger.info("加密后的的签名字符串：" + sign);

        // 请求
        String response = "";
        try {
            response = HttpUtils.postWithStringEntity(PAY_URL,commtiPayXml);
        } catch (Exception e) {
            logger.info("调用微信失败 orderNum:{}",order.getOrderNum());
            return StringUtils.EMPTY;
        }
        logger.info("请求/pay/unifiedorder下单接口后返回数据：" + response);

        //处理请求结果
        Map<String,String>ret = Maps.newHashMap();
        try {
            ret = WXPayAssistUtil.xmlToMap(response);
        } catch (Exception e) {
            logger.info("处理请求结果 orderNum:{} response:{}",order.getOrderNum(),response);
            return StringUtils.EMPTY;
        }

        //获取结果
        if ("SUCCESS".equals(ret.get("return_code")) && "SUCCESS".equals(ret.get("result_code"))) {
            logger.info("微信支付统一下单请求成功，获得的Prepay_id是:{}",ret.get("prepay_id") );
        } else {
            logger.error("微信支付统一下单请求错误：" + ret.get("err_code") + ret.get("err_code_des"));
            return StringUtils.EMPTY;
        }


        //二次签名返回给APP
        String time = Long.toString(System.currentTimeMillis());
        Map<String, String> back = Maps.newHashMap();
        back.put("appid",WX_APPID);
        back.put("timestamp",time);
        back.put("prepayid",ret.get("prepay_id"));
        back.put("nonceStr", nonceStr);
        back.put("package", "Sign=WXPay" );

        String retSign = "";
        try {
           retSign = WXPayAssistUtil.generateSignature(back,WX_PAY_KEY);
        } catch (Exception e) {
            logger.info("二次签名失败 orderNum:{}",order.getOrderNum());
            return StringUtils.EMPTY;
        }
        back.put("paySign",retSign);
        return JsonUtils.toString(back);
    }
}
